package com.yjxz.shop.common.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import com.yjxz.shop.common.Constant;
import org.ocpsoft.prettytime.PrettyTime;


public class DateUtil {

    private DateUtil() {
        throw new RuntimeException();
    }

    /**
     * 生成一个相对时间，如：3分钟前, 刚刚 等...
     * 
     * @param date
     * @return
     */
    public static String formatWithPrettyTime(Date date) {
        PrettyTime p = new PrettyTime(Locale.CHINESE);
        return p.format(date).replaceAll(" ", "");
    }

    /**
     * Date -> String
     */
    public static String format(Date date) {
        return format(date, Constant.DATE_FULL_PATTERN);
    }

    public static String format(Date date, String pattern) {
        return new SimpleDateFormat(pattern).format(date);
    }

    /**
     * String -> Date
     * 
     * @throws ParseException
     */
    public static Date parse(String dateStr) {
        return parse(dateStr, Constant.DATE_FULL_PATTERN);
    }

    public static Date parse(String dateStr, String pattern) {
        try {
            return new SimpleDateFormat(pattern).parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据指定参数返回当前的年|月|日|时|分|秒
     */
    // 如果一个枚举定义成内部类，在访问时直接通过外部类.枚举类名即可。
    public enum DateType {
        YEAR, MONTH, DAY, HOUR, MINUTE, SECOND;
    }

    public static int get(DateType dateType) {
        if (dateType == null) {
            return -1;
        }
        Calendar calendar = Calendar.getInstance();
        switch (dateType) {
            case YEAR:
                return calendar.get(Calendar.YEAR);
            case MONTH:
                return calendar.get(Calendar.MONTH) + 1;
            case DAY:
                return calendar.get(Calendar.DAY_OF_MONTH);
            case HOUR:
                return calendar.get(Calendar.HOUR);
            case MINUTE:
                return calendar.get(Calendar.MINUTE);
            case SECOND:
                return calendar.get(Calendar.SECOND);
            default:
                // 待优化的魔法数字
                return -1;
        }
    }

    public static void main(String[] args) throws ParseException {
        System.out.println(DateUtil.format(new Date(), "HH:mm:ss"));

        String str = "2018年8月8日";
        Date date = DateUtil.parse(str, "yyyy年MM月dd日");
        System.out.println(date);

        int result = DateUtil.get(DateType.YEAR);
        System.out.println(result);
    }
}
